﻿using BaseDal;
using Models;
using Models.QueryParam;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaseBll
{
    public class PurchaseGetBll
    {
        private static readonly Lazy<PurchaseGetBll> dal = new Lazy<PurchaseGetBll>(() => new PurchaseGetBll());

        public static PurchaseGetBll Instance { get; } = dal.Value;

        private PurchaseGetBll() { }

        /// <summary>
        /// 查询数据是否存在
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public bool IsExist(string strWhere)
        {
            return PurchaseGetDal.Instance.IsExist(strWhere);
        }

        /// <summary>
        /// 查询分页数据
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="strWhere"></param>
        /// <param name="filedOrder"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public DataTable GetPageList(int pageSize, int pageIndex, string strWhere, string filedOrder, out int recordCount)
        {
            return PurchaseGetDal.Instance.GetPageList(pageSize, pageIndex, strWhere, filedOrder, out recordCount);
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public List<PurchaseGetHead> GetList(string strWhere)
        {
            return PurchaseGetDal.Instance.GetList(strWhere);
        }

        /// <summary>
        /// 根据id查询实体类
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public PurchaseGetHead GetModelById(decimal id)
        {
            return PurchaseGetDal.Instance.GetModelById(id);
        }

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public bool AddPurchaseGet(PurchaseGetHead model)
        {
            return PurchaseGetDal.Instance.AddPurchaseGet(model);
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool UpdatePurchaseGet(PurchaseGetHead model)
        {
            return PurchaseGetDal.Instance.UpdatePurchaseGet(model);
        }

        /// <summary>
        /// 删除一条数据，及子表所有相关数据
        /// </summary>
        public bool DeletePurchaseGet(int ID)
        {
            return PurchaseGetDal.Instance.DeletePurchaseGet(ID);
        }

        /// <summary>
        /// 修改状态（0：审批中；1：已审批；2：暂存）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int UpdateStatus(int id, int status)
        {
            return PurchaseGetDal.Instance.UpdateStatus(id, status);
        }

        // 定义一个私有的对象作为锁
        private readonly object _lockObject = new object();

        /// <summary>
        /// 审核通过时，修改申请单中的到货数量
        /// </summary>
        /// <param name="getList"></param>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public void UpdRequestWithAudit(List<PurchaseGetBody> getList, decimal orderId)
        {
            List<PurchaseOrderBody> poBList = new List<PurchaseOrderBody>();
            if (getList != null && getList.Count > 0 && orderId > 0)
            {
                // 根据订单ID获取订单对象
                PurchaseOrderHead poHModel = PurchaseOrderBll.Instance.GetModelById(orderId);
                if (poHModel != null && poHModel.ItemList != null && poHModel.ItemList.Count > 0)
                {
                    poBList.AddRange(poHModel.ItemList.FindAll(a => !string.IsNullOrEmpty(a.PO_ApplyNo)));
                }
            }
            //PurchaseRequestHead
            List<PurchaseRequestBody> prBList = new List<PurchaseRequestBody>();
            PurchaseRequestBody prBModel = null;
            if (poBList.Count > 0)
            {
                lock (_lockObject)
                {
                    foreach (PurchaseOrderBody poBModel in poBList)
                    {
                        PurchaseRequestHead prHModel = PurchaseRequestBll.Instance.GetModelByNo(poBModel.PO_ApplyNo);
                        if(prHModel != null)
                        {
                            foreach (var pgBModel in getList)
                            {
                                if (poBModel.PO_ItemID.Equals(pgBModel.PG_ItemID))
                                {
                                    prBModel = new PurchaseRequestBody
                                    {
                                        HeadID = prHModel.ID,
                                        PR_ItemID = pgBModel.PG_ItemID,
                                        PR_GetQty = pgBModel.PG_ArrivalQty
                                    };
                                    break;
                                }
                            }
                        }
                        
                        if (prBModel != null)
                        {
                            prBList.Add(prBModel);
                        }
                    }
                    if (prBList.Count > 0)
                    {
                        bool res = PurchaseGetDal.Instance.UpdateGetQtyFromRequest(prBList);

                    }
                }

            }
        }

        /// <summary>
        /// 验证model各字段合法性
        /// </summary>
        /// <param name="model"></param>
        /// <param name="msg">错误信息</param>
        /// <returns></returns>
        public bool VerifyModel(PurchaseGetHead model, ref string msg)
        {
            string strWhere;
            if (model.ID > 0)
            {
                strWhere = " and PG_Number='" + model.PG_Number + "' and ID !=" + model.ID;
            }
            else
            {
                strWhere = " and PG_Number='" + model.PG_Number + "'";
            }
            if (IsExist(strWhere))
            {
                msg = "收货编号已存在";
                return false;
            }

            // 如果关联订单，则验证数量，不能超过订单的数量  TODO

            // 获取公司名称
            Department company = DeptBll.Instance.GetModelById(model.PG_CompanyId);
            if (company != null)
            {
                model.PG_CompanyName = company.FullName;
            }
            else
            {
                msg = "所选公司不存在";
                return false;
            }

            // 获取部门名称
            Department dept = DeptBll.Instance.GetModelById(model.PG_DeptId);
            if (dept != null)
            {
                model.PG_DeptName = dept.FullName;
            }
            else
            {
                msg = "所选部门不存在";
                return false;
            }

            if (model.PG_OrderID <= 0)
            {
                msg = "请选择采购订单";
                return false;
            }

            // 根据订单ID获取订单对象
            List<PurchaseOrderHead> poHModelList = PurchaseOrderBll.Instance.GetList(" and ID = " + model.PG_OrderID);
            PurchaseOrderHead poHModel = null;
            if (poHModelList != null && poHModelList.Count > 0)
            {
                poHModel = poHModelList[0];
                model.PG_OrderNo = poHModel.PO_OrderNo;
                model.PG_SupplierId = poHModel.PO_SupplierId;
                model.PG_SupplierName = poHModel.PO_SupplierName;
            }
            else
            {
                msg = "所选采购订单不存在";
                return false;
            }

            return true;
        }

        /// <summary>
        /// 获得查询条件
        /// </summary>
        /// <param name="context">上下文</param>
        /// <returns>查询条件</returns>
        /// <remarks>edit 20190428 liuyan</remarks>
        public string GetListWhere(PurchaseGetQuery queryParams, ref string msg)
        {
            StringBuilder strWhere = new StringBuilder("");

            if (!string.IsNullOrEmpty(queryParams.Number))
            {
                strWhere.Append(" and PG_Number like '%" + queryParams.Number + "%'");
            }
            if (!string.IsNullOrEmpty(queryParams.Person))
            {
                strWhere.Append(" and PG_Person like '%" + queryParams.Person + "%'");
            }
            if (queryParams.DeptId != 0)
            {
                strWhere.Append(" and PG_DeptId = " + queryParams.DeptId);
            }
            if (queryParams.AuditStatus != -1)
            {
                strWhere.Append(" and PG_AuditStatus = " + queryParams.AuditStatus);
            }
            if (!string.IsNullOrEmpty(queryParams.Date))
            {
                if (DateTime.TryParse(queryParams.Date, out DateTime parsedDate))
                {
                    strWhere.Append(" and PG_Date = '" + queryParams.Date + "'");
                }
                else
                {
                    msg = "无效的日期格式";
                    return null;
                }
            }
            if (!string.IsNullOrEmpty(queryParams.SupplierName))
            {
                strWhere.Append(" and PG_SupplierName like '%" + queryParams.SupplierName + "%'");
            }

            return strWhere.ToString();
        }

    }
}
